<?php
namespace app\api\controller;
use app\common\controller\Api;
use think\Log;
use think\Cache;
use addons\third\library\Service;
use WeChatPay\Builder;
use EasyWeChat\Factory;
use addons\third\model\Third;
use app\common\model\Prize;

class Weixin extends Api
{
  protected $noNeedLogin = ['weilogin', 'weiPay', 'handlePayNotify'];
  protected $noNeedRight = '*';
  protected $appId = 'wxe2a219a14b77bd56';
  protected $appSecret = '49136f1c7729db4727531b520932271f';

  public function _initialize()
  {
    parent::_initialize();

    $this->app = Factory::payment([
      // 必要配置
      'app_id' => $this->appId,
      'mch_id' => '1680143925',
      'key' => 'Shanghonghaofanhongyan1234567890',   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
      // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
      'cert_path' => 'merchant/apiclient_cert.pem', // XXX: 绝对路径！！！！
      'key_path' => 'merchant/apiclient_key.pem',      // XXX: 绝对路径！！！！
      'notify_url' => 'https://where.hhsh999.com/api/weixin/handlePayNotify',
    ]);
    
    $user = $this->auth->getUser();
    Log::record(113);
    Log::record($user);
    $user && $this->uid = $user->id;
    
  }
  
//   查询我的打赏
public function getMyPrize(){
    $total = Prize::where('paid', 1)->where('userid', $this->uid)->sum('money');
    // 计算排名
    $list = Prize::where('paid', 1)->field("userid,sum(money) as totalMoney")->group('userid')->order('totalMoney', 'desc')->select();
    Log::record('$list');
    Log::record($list);
    $index = 0;
    foreach ($list as $key => $value) {
        if ($value->userid == $this->uid) {
                $index = $key + 1;
            }
        };
        $index === 0 && $index = '--';
    $this->success('查询成功', ['total' => $total, 'index' => $index, 'list' => $list]);
}
  
//   统计排名列表
public function getRankList(){
    $list = Prize::where('paid', 1)->alias('p')->join('User u', 'u.id = p.userid')->field("u.nickname,p.id, u.avatar,u.bio,sum(p.money) as totalMoney")->group('p.userid')->order('totalMoney', 'desc')->select();
    $this->success('查询排名成功', $list);
}
  
//   查询实时打赏
public function getPrizeList(){
    Log::record(222);
    Log::record($this->uid);
    $list = Prize::where('paid', 1)->alias('p')->join('User u', 'u.id = p.userid')->field('u.nickname,p.money, p.create_time, p.id, u.avatar')->order('create_time', 'desc')->paginate();
    $this->success('查询实时打赏成功', $list);
}


  public function handlePayNotify()
  {
    $response = $this->app->handlePaidNotify(function ($message, $failure) {
      Log::record(112);
      Log::record($message);
      
      $order = Prize::where('out_trade_no', $message['out_trade_no'])->find();
      Log::record($order);

      if (!$order || $order->paid) { // 如果订单不存在 或者 订单已经支付过了
        return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
      }

      if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
        // 用户是否支付成功
        if ($message['result_code'] === 'SUCCESS') {
            $order->paid = true;
            
        } elseif ($message['result_code'] === 'FAIL') {
         
        }
      } else {
        return $failure('通信失败，请稍后再通知我');
      }
      
      $order->save(); // 保存订单

      return true; // 返回处理完成
    });
   
  }

  public function weiPay()
  {
    $money = $this->request->post("money");
    $msg = $this->request->post("msg");

    $uid = $this->auth->getUser()->id;
    Log::record($uid);
    Log::record(date("YmdHis") . mt_rand(100, 999));
    // 根据uid查询openid
    $third = Third::where('user_id', $uid)->find();
    if (!$third) {
      $this->error('三方登录不存在');
    }
    $openid = $third->openid;
    Log::record('$openid');
    Log::record($openid);
    if (!$openid) {
      $this->error('openid不存在');
    }
    $out_trade_no = date("YmdHis") . mt_rand(100, 999);
    Log::record($out_trade_no);
    $result = $this->app->order->unify([
      'body' => $msg,
      'out_trade_no' => $out_trade_no,
      'total_fee' => $money * 100,
      // 'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
      // 'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
      'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
      'openid' => $openid,
    ]);


    Log::record('$result212121212121');
    Log::record($result);

    if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
      $prepayId = $result['prepay_id'];

      // 获取前端发起支付所需的配置信息
      $jsConfig = $this->app->jssdk->bridgeConfig($prepayId, false);
      
      //   创建订单
      Prize::create(['userid' => $uid, 'money' => $money * 100, 'out_trade_no' => $out_trade_no]);
    

      // 将 $jsConfig 传递给前端
      $this->success('发起支付成功', $jsConfig);
    } else {
      $this->error('发起支付异常');
    }


  }

  public function weilogin()
  {
    $code = $this->request->post("code");
    $inviteId = $this->request->post("inviteId");
    $inviteId == 'undefined' && $inviteId = 0;
    Log::record(8888888);
    Log::record($code);
    Log::record($inviteId);
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appId}&secret={$this->appSecret}&code={$code}&grant_type=authorization_code";
    $result = json_decode(file_get_contents($url), true);
    Log::record($result);
    if (isset($result['access_token'])) {
      // 拉取用户信息
      $url_u = "https://api.weixin.qq.com/sns/userinfo?access_token={$result['access_token']}&openid={$result['openid']}&lang=zh_CN";
      $result_u = json_decode(file_get_contents($url_u), true);
      Log::record($result_u);

      $ret = Service::connect('wechat', $result_u, $result, 0, $inviteId, $this->auth->getUser());
      Log::record(336);
      Log::record($ret);
      
      if(is_bool($ret)){
         if ($ret) {
            $this->success('微信登录成功', ['userinfo' => $this->auth->getUserinfo()]);
          } else {
            $this->error('微信登录失败');
          }
      }else{
          if ($ret[0]) {
              if($ret[1]){
                  $this->success('微信登录成功', ['userinfo' => $this->auth->getUserinfo(), 'isFirst' => true]);
              }else{
                  $this->success('微信登录成功', ['userinfo' => $this->auth->getUserinfo()]);
              }
            
          } else {
            $this->error('微信登录失败');
          }
      }
      

    }

    $this->error('access_token异常');
  }

  // 示例代码，仅供参考
  public function getAccessToken($appId, $appSecret)
  {
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
    $result = json_decode(file_get_contents($url));
    if (isset($result->access_token) && $result->access_token) {
      // 缓存access_token
      return $result->access_token;
    }
    return null;
  }

  public function getJsapiTicket($accessToken)
  {
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$accessToken}";
    $result = json_decode(file_get_contents($url));
    if (isset($result->ticket) && $result->ticket) {
      // 缓存jsapi_ticket
      return $result->ticket;
    }
    return null;
  }

  // 获取签名信息
  public function getSignPackage()
  {
    Log::record(6666666666);
    $url = $this->request->post('url');
    $url = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
    Log::record($url);
    // 缓存签名信息，这里以URL为key，签名数组为value
    $cacheKey = 'wx_sign_' . md5($url);
    Log::record($cacheKey);
    $signPackage = Cache::get($cacheKey);
    Log::record($signPackage);
    if (!$signPackage) {
      // 生成accessToken
      $accessToken = $this->getAccessToken($this->appId, $this->appSecret);
      Log::record(434343434);
      Log::record($accessToken);
      $jsapiTicket = $this->getJsapiTicket($accessToken);
      Log::record($jsapiTicket);

      $nonceStr = $this->createNonceStr();
      $timestamp = time();

      $string1 = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
      $signature = sha1($string1);
      $signPackage = [
        'appId' => $this->appId,
        'timestamp' => $timestamp,
        'nonceStr' => $nonceStr,
        'signature' => $signature,
      ];
      Cache::set($cacheKey, $signPackage, 300); // 缓存300秒

      $this->success('查询成功', Cache::get($cacheKey));
    }

    $this->success('查询成功', $signPackage);
  }

  // 生成随机字符串
  private function createNonceStr($length = 16)
  {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $str = '';
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }
}